Using an External Script File

Sometimes, the JavaScript script that you create in an HTML document may extend to tens and hundreds of lines. This may affects the readability of the HTML document. Moreover, you may want to use the same script in several Web pages. Despite of this, creating the script in an HTML document for all those Web pages is rather cumbersome. In such a situation, you can create an external script file rather than crating the script inside an HTML document. After creating the external script file, you need to link it with the HTML document by sung the <script> tag.

Let’s do the following steps to use an external script file to add a script:

Creating an External Script File


document.write(“Using an external script file to add a Script”);

in this code, the document object and the write() method is used to display a textual message on the Web page.

Click File->Save in the Notepad window or press the Ctrl+S keys from the keyboard. The Save As dialog box appears

Select the desired location for saving the file in the Save As dialog box.

Select All Files from the Save as type box.

In the File name box, type an appropriate name for the file along with the .js extension. And name with myScript.js.

Open another blank document in Notepad and write the code, given below:


<!DOCTYPE html>
<html>
<head>
    <title>JavaScriptExample<title>
</head>
<body bgcolor=”gray”>
<center>
    <h1>JavaScript</h1>
    <script src=”myScript.js”></script>
</center>
</body>
</html>

In this example, the <script> and </script> tags are enclosed in the body section of the HTML document. The src attribute of the <script> tag is set to the URL of the script file. If the script file is in the same folder as the HTML document, then you need to specify the name of the script file. However, if the script file and the HTML document are in different folders, then you need to specify the complete URL of the script file. Note that there is no script code written between the <script> and </script> tags. In case you have written any script code within the <script> tag that code is not processed and therefore, ignored by the Web browser.

Save the document with the name addExternalScript.html open with the browser.

Let’s now learn how to handle the scripts in Web browsers that do not support JavaScript.